package com.von.interceptor;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.von.ann.TokenCheck;
import com.von.entity.Role;
import com.von.enums.ErrorEnum;
import com.von.exceptions.BusinessRuntimeException;
import com.von.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author pengzhaofeng
 * @date 2020-05-26 20:41
 */
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtils redisUtils;

    @Value(value = "${token.expired.time}")
    private long tokenExpiredTime;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        String uri = httpServletRequest.getRequestURI();
        //取出token
        String token = httpServletRequest.getHeader("token");
        if (token != null) {
            redisUtils.expire(token, tokenExpiredTime);
        }
        // 如果不是映射到方法直接通过
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();
        //检查有没有需要用户权限的注解
        if (method.getDeclaringClass().isAnnotationPresent(TokenCheck.class) || method.isAnnotationPresent(TokenCheck.class)) {
            if (token == null) {
                throw new BusinessRuntimeException(ErrorEnum.TOKEN_ERROR);
            }
            String s = redisUtils.get(token);
            if (s == null) {
                throw new BusinessRuntimeException(ErrorEnum.TOKEN_ERROR);
            }
            List<Integer> tokenRoles = JSONUtil.parseArray(JSONUtil.parseObj(s).get("role")).toList(Role.class).stream().map(Role::getId).collect(Collectors.toList());
            List<Integer> urlRoles = JSONUtil.parseArray(redisUtils.getValue("authority", uri)).toList(Integer.class);
            tokenRoles.retainAll(urlRoles);
            //检测权限
            if (CollectionUtil.isNotEmpty(urlRoles) && CollectionUtil.isEmpty(tokenRoles)) {
                throw new RuntimeException("权限不足");
            }
            return true;
        }
        //未添加注解默认允许访问
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
